
package cn.edu.zut.soft.graduate.websocket;

import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;


/**
 * Socket建立连接（握手）和断开
 *
 * @author cc
 * @Date 2016/11/15
 * @value 1.0
 */
public class HandShake implements HandshakeInterceptor {

    private static final String USER = "user";

    private Logger logger = LoggerFactory.getLogger(getClass());

    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        logger.info("Websocket:用户[" + ((LoginVO)((ServletServerHttpRequest) request).getServletRequest().getSession(false).getAttribute("user")).getName() + "]已经建立连接");
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpSession session = servletRequest.getServletRequest().getSession(false);
        // 标记用户
        LoginVO loginVO = (LoginVO) session.getAttribute(USER);
        if (loginVO != null) {
            attributes.put(USER, loginVO);
        } else {
            return false;
        }
        return true;
    }

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }

}
